<!--created by yuyupeng-->
<!--2023/02/20-->
<!-- 岗位管理-->
<template>
  <div class="list-card-container">
    <a-card title="岗位管理" class="general-card">
      <!-- 查询表单 -->
      <AdvancedSearch
        ref="searchRef"
        :data-source="searchItemList"
        @change="searchByParams"
      />
      <a-space style="margin-top: 5px; margin-bottom: 5px">
        <AdvancedDrawer
          click="button"
          title="新增岗位信息"
          clickword="新增岗位"
          :rules="advancedDrawerRules"
          :data-source="addDrawerConfig"
          @change="addDrawerSubmit"
        />
        <a-popconfirm
          content="确定删除吗?"
          type="warning"
          @ok="deleteTbDataList(selectedKeys)"
        >
          <a-button :disabled="selectedKeys.length === 0"
            ><icon-delete />批量删除</a-button
          >
        </a-popconfirm>
        <a-button @click="exportToExcel"><icon-download />导出Excel</a-button>
      </a-space>
      <!-- 表格 -->
      <a-table
        v-model:selectedKeys="selectedKeys"
        row-key="id"
        column-resizable
        :columns="tbCols"
        :data="tbData"
        :row-selection="rowSelection"
        :pagination="pagination"
        :loading="tbLoading"
        :scroll="{ x: '100%', y: 600 }"
        :scrollbar="true"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 插槽-详情 -->
        <template #detail="{ record }">
          <AdvancedShower
            click="link"
            title="岗位详情"
            clickword="详情"
            :data-source="showDrawerConfig"
            :data-record="record"
          />
        </template>
        <!-- 插槽-一键复制 -->
        <template #quickCopyToolTip="{ record, column }">
          <quick-copy-tool-tip
            :show-text="record[column['dataIndex']]"
            show-btn
          />
        </template>
        <!-- 插槽-状态 -->
        <template #status="{ record }">
          <a-tag v-if="record.status === 1" color="#86909c">停用</a-tag>
          <a-tag v-else-if="record.status === 0" color="#00b42a">正常</a-tag>
        </template>
        <!-- 插槽-操作 -->
        <template #operation="{ record }">
          <a-space>
            <AdvancedDrawer
              click="link"
              title="修改岗位信息"
              clickword="修改"
              :rules="advancedDrawerRules"
              :data-source="editDrawerConfig"
              :data-record="record"
              @change="editDrawerSubmit"
            />
            <a-popconfirm
              content="确定删除吗?"
              type="warning"
              @ok="deleteTbData(record.id)"
            >
              <a-link type="text">删除</a-link>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import { Notification } from '@arco-design/web-vue';
  import { PostRecord, PostParams } from '@/api/system/model/postModel';
  import dayjs from 'dayjs';
  import {
    queryPostRecordList,
    addPostRecord,
    editPostRecord,
    deletePostRecords,
    exportDataToExcel,
  } from '@/api/system/post';
  import { ref, onMounted, reactive } from 'vue';
  import AdvancedSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';
  import AdvancedShower from '@/common/components/cac-components/advanced-shower/index.vue';
  import QuickCopyToolTip from '@/common/components/cac-components/quickcopy-tooltip/index.vue';
  import { Pagination } from '@/types/global';

  /**
   * data
   */
  // 表格
  const tbData = ref<PostRecord[]>([]);
  const tbCols = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    },
    /* {
      title: '岗位ID',
      dataIndex: 'id',
      fixed: 'left',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    }, */
    {
      title: '查看',
      fixed: 'left',
      align: 'center',
      width: 100,
      slotName: 'detail',
    },
    {
      title: '岗位编码',
      dataIndex: 'code',
      ellipsis: true,
      tooltip: true,
      width: 150,
      align: 'center',
      slotName: 'quickCopyToolTip',
    },
    {
      title: '岗位名称',
      dataIndex: 'name',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
      slotName: 'quickCopyToolTip',
    },
    /* {
      title: '显示顺序',
      dataIndex: 'sort',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    }, */
    {
      title: '状态',
      dataIndex: 'status',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
      slotName: 'status',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
      slotName: 'quickCopyToolTip',
    },
    {
      title: '所属部门ID',
      dataIndex: 'deptId',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
      slotName: 'quickCopyToolTip',
    },
    {
      title: '所属组织机构ID',
      dataIndex: 'orgId',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
      slotName: 'quickCopyToolTip',
    },
    /* {
      title: '创建者',
      dataIndex: 'creator',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    },
    {
      title: '更新者',
      dataIndex: 'updater',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    },
    {
      title: '更新ip',
      dataIndex: 'updateIp',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    },
    {
      title: '是否删除',
      dataIndex: 'deleted',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    },
    {
      title: '数据密级(0:公开,5内部,6秘密,7机密,8绝密)',
      dataIndex: 'secretLevel',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    },
    {
      title: '乐观锁',
      dataIndex: 'version',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    }, */
    {
      title: '租户编号',
      dataIndex: 'tenantId',
      ellipsis: true,
      tooltip: true,
      width: 180,
      align: 'center',
      slotName: 'quickCopyToolTip',
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 120,
      slotName: 'operation',
    },
  ];
  const searchRef = ref<any>();
  const tbLoading = ref<boolean>(false);
  // 勾选框
  const selectedKeys = ref([]);
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 搜索项配置
  const searchItemList = [
    // { type: 'text', labelText: '岗位ID', fieldName: 'id' },
    { type: 'text', labelText: '岗位编码', fieldName: 'code' },
    { type: 'text', labelText: '岗位名称', fieldName: 'name' },
    // { type: 'text', labelText: '显示顺序', fieldName: 'sort' },
    {
      type: 'select',
      labelText: '状态',
      fieldName: 'status',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
    },
    /* { type: 'text', labelText: '备注', fieldName: 'remark' },
    { type: 'text', labelText: '所属部门ID', fieldName: 'deptId' },
    { type: 'text', labelText: '所属组织机构ID', fieldName: 'orgId' },
    { type: 'text', labelText: '创建者', fieldName: 'creator' },
    { type: 'text', labelText: '创建时间', fieldName: 'createTime' },
    { type: 'text', labelText: '更新者', fieldName: 'updater' },
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime' },
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp' },
    { type: 'text', labelText: '是否删除', fieldName: 'deleted' },
    {
      type: 'text',
      labelText: '数据密级(0:公开,5内部,6秘密,7机密,8绝密)',
      fieldName: 'secretLevel',
    },
    { type: 'text', labelText: '乐观锁', fieldName: 'version' },
    /* { type: 'text', labelText: '租户编号', fieldName: 'tenantId' }, */
  ];
  // 新增抽屉配置项
  const addDrawerConfig = [
    { type: 'text', labelText: '岗位编码', fieldName: 'code' },
    { type: 'text', labelText: '岗位名称', fieldName: 'name' },
    {
      type: 'number',
      labelText: '显示顺序',
      fieldName: 'sort',
      initialValue: 0,
    },
    {
      type: 'select',
      labelText: '状态',
      fieldName: 'status',
      codefield: 'value',
      namefield: 'label',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
      initialValue: 0,
    },
    { type: 'text', labelText: '备注', fieldName: 'remark' },
    { type: 'text', labelText: '所属部门ID', fieldName: 'deptId' },
    { type: 'text', labelText: '所属组织机构ID', fieldName: 'orgId' },
    /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
    /* { type: 'text', labelText: '租户编号', fieldName: 'tenantId' }, */
  ];
  // 修改抽屉配置项
  const editDrawerConfig = [
    { type: 'text', labelText: 'id', fieldName: 'id', disabled: true },
    { type: 'text', labelText: '岗位编码', fieldName: 'code' },
    { type: 'text', labelText: '岗位名称', fieldName: 'name' },
    {
      type: 'number',
      labelText: '显示顺序',
      fieldName: 'sort',
    },
    {
      type: 'select',
      labelText: '状态',
      fieldName: 'status',
      codefield: 'value',
      namefield: 'label',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
    },
    { type: 'text', labelText: '备注', fieldName: 'remark' },
    { type: 'text', labelText: '所属部门ID', fieldName: 'deptId' },
    { type: 'text', labelText: '所属组织机构ID', fieldName: 'orgId' },
    /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
    /* { type: 'text', labelText: '租户编号', fieldName: 'tenantId' }, */
  ];
  // 抽屉表单项校验配置
  const advancedDrawerRules = ref({
    code: [{ required: true, message: '请输入岗位编码' }],
    name: [{ required: true, message: '请输入岗位名称' }],
    sort: [{ required: true, message: '请输入显示顺序' }],
  });
  // 详情抽屉配置项
  const showDrawerConfig = [
    { type: 'text', labelText: '岗位ID', fieldName: 'id' },
    { type: 'text', labelText: '岗位编码', fieldName: 'code' },
    { type: 'text', labelText: '岗位名称', fieldName: 'name' },
    { type: 'number', labelText: '显示顺序', fieldName: 'sort' },
    {
      type: 'select',
      labelText: '状态',
      fieldName: 'status',
      codefield: 'value',
      namefield: 'label',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
    },
    { type: 'text', labelText: '备注', fieldName: 'remark' },
    { type: 'text', labelText: '所属部门ID', fieldName: 'deptId' },
    { type: 'text', labelText: '所属组织机构ID', fieldName: 'orgId' },
    /* { type: 'text', labelText: '创建者', fieldName: 'creator' },
    { type: 'text', labelText: '创建时间', fieldName: 'createTime' },
    { type: 'text', labelText: '更新者', fieldName: 'updater' },
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime' },
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp' },
    { type: 'text', labelText: '是否删除', fieldName: 'deleted' },
    {
      type: 'text',
      labelText: '数据密级(0:公开,5内部,6秘密,7机密,8绝密)',
      fieldName: 'secretLevel',
    },
    { type: 'text', labelText: '乐观锁', fieldName: 'version' }, */
    /* { type: 'text', labelText: '租户编号', fieldName: 'tenantId' }, */
  ];
  /**
   * func
   */
  /**
   * @method
   * @description 获取表格数据
   */
  const getTbDataByPage = async (reqdata: any = {}) => {
    const params: PostParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...reqdata,
    };
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      const { data } = await queryPostRecordList(params);
      tbData.value = data.list;
      pagination.total = Number(data.total); // 用Number函数转一下，否则f12控制台会有警告，很不好看
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: any = {}) => {
    getTbDataByPage(reqdata);
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    console.log(pageSize);
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 新增抽屉提交
   */
  const addDrawerSubmit = async (reqdata: any) => {
    console.log(reqdata);
    try {
      const res = (await addPostRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '保存成功！',
        });
      } else {
        Notification.error({
          title: '保存失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 修改抽屉提交
   */
  const editDrawerSubmit = async (reqdata: any) => {
    console.log(reqdata);
    try {
      const res = (await editPostRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '修改成功！',
        });
      } else {
        Notification.error({
          title: '修改失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 删除岗位信息
   */
  const deleteTbData = async (id: string) => {
    const reqdata = [];
    reqdata.push(id);
    try {
      const res = (await deletePostRecords(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 批量删除岗位信息，传id数组，支持批量
   */
  const deleteTbDataList = async (ids: string[]) => {
    try {
      const res = (await deletePostRecords(ids)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 导出到Excel
   */
  const exportToExcel = async () => {
    try {
      const res = (await exportDataToExcel()) as any;
      console.log(res);
      if (res.code === null || res.code === undefined) {
        const elink = document.createElement('a');
        elink.download = `岗位信息导出数据${dayjs()
          .format('YYYY-MM-DD_HH:mm:ss')
          .toString()}.xlsx`;
        elink.style.display = 'none';
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        console.log(blob);
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      } else {
        // 正常情况下文件的下载是不会返回retCode的，如果发现有返回码，说明就是接口出了问题
        Notification.error({
          title: '导出失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * onMounted
   */
  onMounted(() => {
    getTbDataByPage();
  });
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    // background-color: var(--color-bg-1);
    border-radius: var(--border-radius-default);
  }
</style>
